<template>
  <div class="app-container">
    <n-layout has-sider class="layout">
      <!-- 左侧目录树 -->
      <n-layout-sider
        bordered
        collapse-mode="width"
        :collapsed-width="64"
        :width="240"
        show-trigger
        :native-scrollbar="false"
      >
        <div class="sidebar-header">
          <h3>目录</h3>
          <n-button size="small" @click="showAddFolderModal = true">
            <template #icon>
              <n-icon><Add /></n-icon>
            </template>
            添加
          </n-button>
        </div>
        
        <n-tree
          block-line
          :data="folderTree"
          :selected-keys="selectedFolderKeys"
          :expanded-keys="expandedKeys"
          @update:selected-keys="handleFolderSelect"
          @update:expanded-keys="handleExpandedChange"
          key-field="key"
          label-field="label"
          children-field="children"
        />
      </n-layout-sider>

      <!-- 右侧任务区域 -->
      <n-layout-content>
        <div class="content-header">
          <h2>{{ currentFolderName || '全部任务' }}</h2>
          <n-button type="primary" @click="showAddTaskModal = true" :disabled="!selectedFolderKeys.length">
            <template #icon>
              <n-icon><Add /></n-icon>
            </template>
            新建任务
          </n-button>
        </div>

        <div class="task-list">
          <draggable
            v-model="currentTasks"
            item-key="id"
            @end="handleDragEnd"
            class="task-draggable"
          >
            <template #item="{ element: task }">
              <div class="task-item" :class="{ completed: task.completed }">
                <n-checkbox
                  :checked="task.completed"
                  @update:checked="toggleTaskStatus(task)"
                />
                <div class="task-content">
                  <div class="task-title">{{ task.title }}</div>
                  <div class="task-desc" v-if="task.description">{{ task.description }}</div>
                </div>
                <div class="task-actions">
                  <n-button size="small" quaternary @click="editTask(task)">
                    <n-icon><Edit /></n-icon>
                  </n-button>
                  <n-button size="small" quaternary type="error" @click="deleteTask(task)">
                    <n-icon><Delete /></n-icon>
                  </n-button>
                </div>
              </div>
            </template>
          </draggable>
        </div>

        <div v-if="!currentTasks.length" class="empty-state">
          <n-empty description="暂无任务，点击右上角添加新任务" />
        </div>
      </n-layout-content>
    </n-layout>

    <!-- 添加目录弹窗 -->
    <n-modal v-model:show="showAddFolderModal">
      <n-card style="width: 400px" title="添加目录" :bordered="false">
        <n-form ref="folderFormRef" :model="folderForm">
          <n-form-item label="目录名称">
            <n-input v-model:value="folderForm.name" placeholder="请输入目录名称" />
          </n-form-item>
          <n-form-item label="父目录">
            <n-tree-select
              v-model:value="folderForm.parentKey"
              :options="folderTree"
              placeholder="选择父目录（留空为根目录）"
              clearable
            />
          </n-form-item>
        </n-form>
        <template #footer>
          <n-space justify="end">
            <n-button @click="showAddFolderModal = false">取消</n-button>
            <n-button type="primary" @click="addFolder">确认</n-button>
          </n-space>
        </template>
      </n-card>
    </n-modal>

    <!-- 添加/编辑任务弹窗 -->
    <n-modal v-model:show="showAddTaskModal">
      <n-card style="width: 500px" :title="editingTask ? '编辑任务' : '添加任务'" :bordered="false">
        <n-form ref="taskFormRef" :model="taskForm">
          <n-form-item label="任务标题">
            <n-input v-model:value="taskForm.title" placeholder="请输入任务标题" />
          </n-form-item>
          <n-form-item label="任务描述">
            <n-input
              v-model:value="taskForm.description"
              type="textarea"
              placeholder="请输入任务描述（可选）"
              :rows="3"
            />
          </n-form-item>
        </n-form>
        <template #footer>
          <n-space justify="end">
            <n-button @click="showAddTaskModal = false">取消</n-button>
            <n-button type="primary" @click="saveTask">确认</n-button>
          </n-space>
        </template>
      </n-card>
    </n-modal>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue'
import { NLayout, NLayoutSider, NLayoutContent, NTree, NButton, NModal, NCard, NForm, NFormItem, NInput, NCheckbox, NSpace, NEmpty, NIcon, NTreeSelect } from 'naive-ui'
import { Add, Edit, Delete } from '@vicons/ionicons5'
import draggable from 'vuedraggable'

export default {
  name: 'App',
  components: {
    NLayout,
    NLayoutSider,
    NLayoutContent,
    NTree,
    NButton,
    NModal,
    NCard,
    NForm,
    NFormItem,
    NInput,
    NCheckbox,
    NSpace,
    NEmpty,
    NIcon,
    NTreeSelect,
    draggable,
    Add,
    Edit,
    Delete
  },
  setup() {
    // 数据存储
    const folders = ref([])
    const tasks = ref([])
    
    // 状态管理
    const selectedFolderKeys = ref([])
    const expandedKeys = ref([])
    const showAddFolderModal = ref(false)
    const showAddTaskModal = ref(false)
    const editingTask = ref(null)
    
    // 表单数据
    const folderForm = ref({
      name: '',
      parentKey: null
    })
    const taskForm = ref({
      title: '',
      description: ''
    })

    // 计算属性
    const folderTree = computed(() => {
      const buildTree = (parentKey = null) => {
        return folders.value
          .filter(folder => folder.parentKey === parentKey)
          .map(folder => ({
            key: folder.key,
            label: folder.name,
            children: buildTree(folder.key)
          }))
      }
      return buildTree()
    })

    const currentFolderName = computed(() => {
      if (!selectedFolderKeys.value.length) return ''
      const folder = folders.value.find(f => f.key === selectedFolderKeys.value[0])
      return folder ? folder.name : ''
    })

    const currentTasks = computed(() => {
      if (!selectedFolderKeys.value.length) return []
      return tasks.value.filter(task => task.folderKey === selectedFolderKeys.value[0])
    })

    // 方法
    const generateKey = () => Date.now().toString()

    const addFolder = () => {
      if (!folderForm.value.name.trim()) return
      
      folders.value.push({
        key: generateKey(),
        name: folderForm.value.name,
        parentKey: folderForm.value.parentKey || null
      })
      
      folderForm.value = { name: '', parentKey: null }
      showAddFolderModal.value = false
      saveData()
    }

    const handleFolderSelect = (keys) => {
      selectedFolderKeys.value = keys
    }

    const handleExpandedChange = (keys) => {
      expandedKeys.value = keys
    }

    const saveTask = () => {
      if (!taskForm.value.title.trim() || !selectedFolderKeys.value.length) return
      
      if (editingTask.value) {
        const task = tasks.value.find(t => t.id === editingTask.value.id)
        if (task) {
          task.title = taskForm.value.title
          task.description = taskForm.value.description
        }
      } else {
        tasks.value.push({
          id: generateKey(),
          title: taskForm.value.title,
          description: taskForm.value.description,
          completed: false,
          folderKey: selectedFolderKeys.value[0],
          order: tasks.value.length
        })
      }
      
      taskForm.value = { title: '', description: '' }
      showAddTaskModal.value = false
      editingTask.value = null
      saveData()
    }

    const editTask = (task) => {
      editingTask.value = task
      taskForm.value = {
        title: task.title,
        description: task.description
      }
      showAddTaskModal.value = true
    }

    const deleteTask = (task) => {
      const index = tasks.value.findIndex(t => t.id === task.id)
      if (index > -1) {
        tasks.value.splice(index, 1)
        saveData()
      }
    }

    const toggleTaskStatus = (task) => {
      task.completed = !task.completed
      saveData()
    }

    const handleDragEnd = () => {
      saveData()
    }

    const saveData = () => {
      localStorage.setItem('todoflow-folders', JSON.stringify(folders.value))
      localStorage.setItem('todoflow-tasks', JSON.stringify(tasks.value))
    }

    const loadData = () => {
      const savedFolders = localStorage.getItem('todoflow-folders')
      const savedTasks = localStorage.getItem('todoflow-tasks')
      
      if (savedFolders) folders.value = JSON.parse(savedFolders)
      if (savedTasks) tasks.value = JSON.parse(savedTasks)
      
      // 默认展开所有目录
      expandedKeys.value = folders.value.map(f => f.key)
    }

    // 初始化
    onMounted(() => {
      loadData()
    })

    return {
      folders,
      tasks,
      folderTree,
      selectedFolderKeys,
      expandedKeys,
      showAddFolderModal,
      showAddTaskModal,
      editingTask,
      folderForm,
      taskForm,
      currentFolderName,
      currentTasks,
      addFolder,
      handleFolderSelect,
      handleExpandedChange,
      saveTask,
      editTask,
      deleteTask,
      toggleTaskStatus,
      handleDragEnd
    }
  }
}
</script>

<style>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  background-color: #f5f5f5;
}

.app-container {
  height: 100vh;
}

.layout {
  height: 100vh;
}

.sidebar-header {
  padding: 16px;
  border-bottom: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.sidebar-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
}

.content-header {
  padding: 20px;
  background: white;
  border-bottom: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.content-header h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
}

.task-list {
  padding: 20px;
  max-width: 800px;
}

.task-draggable {
  min-height: 200px;
}

.task-item {
  display: flex;
  align-items: center;
  padding: 12px 16px;
  background: white;
  border-radius: 8px;
  margin-bottom: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.task-item:hover {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

.task-item.completed {
  opacity: 0.6;
}

.task-item.completed .task-title {
  text-decoration: line-through;
  color: #999;
}

.task-content {
  flex: 1;
  margin-left: 12px;
}

.task-title {
  font-size: 14px;
  font-weight: 500;
  color: #333;
}

.task-desc {
  font-size: 12px;
  color: #666;
  margin-top: 4px;
}

.task-actions {
  display: flex;
  gap: 4px;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.task-item:hover .task-actions {
  opacity: 1;
}

.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 400px;
}

.n-tree {
  padding: 8px;
}
</style>
